package com.anywhere.freightman.system.controller;

import com.anywhere.freightman.common.ContextKeys;
import com.anywhere.freightman.common.annotation.Permission;
import com.anywhere.freightman.common.entity.ReturnResp;
import com.anywhere.freightman.common.entity.user.Account;
import com.anywhere.freightman.common.entity.user.UserQueryEntity;
import com.anywhere.freightman.common.entity.user.request.UserPwdRequest;
import com.anywhere.freightman.common.entity.user.request.UserRequest;
import com.anywhere.freightman.common.enumeration.CommonStatus;
import com.anywhere.freightman.common.enumeration.RoleType;
import com.anywhere.freightman.common.ex.CustomException;
import com.anywhere.freightman.common.request.PageRequest;
import com.anywhere.freightman.system.controller.request.EnableRequest;
import com.anywhere.freightman.system.controller.request.UserRoleRequest;
import com.anywhere.freightman.system.model.UserModel;
import com.anywhere.freightman.system.service.IRoleService;
import com.anywhere.freightman.system.service.IUserService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
@Api(tags = "账号相关")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;

    @PostMapping("login")
    public Account login(@RequestParam("username") String username,
                         @RequestParam("password") String password) {
        return userService.login(username, password);
    }

    @Permission(code = "SYSTEM_ACCOUNT")
    @GetMapping("page")
    @ApiOperation("分页")
    public PageInfo<UserModel> getPageList(HttpServletRequest httpRequest,
                                           UserQueryEntity qm) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        if (!account.getType().equals(RoleType.ADMIN)) {
//            qm.setUserType(account.getType());
            qm.setCompanyId(account.getCompanyId());
        }

        PageRequest<UserQueryEntity> pageRequest = new PageRequest<>();
        BeanUtils.copyProperties(qm, pageRequest);
        qm.setExUserId(account.getId());
        pageRequest.setEntity(qm);

        return userService.getPageList(pageRequest);
    }

    @PostMapping
    @Permission(code = "SYSTEM_ACCOUNT")
    public UserModel insertData(HttpServletRequest httpRequest,
                                @RequestBody UserRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);

        UserModel model = new UserModel();
        if (account.getType().equals(RoleType.ADMIN)) {
            model.setType(RoleType.ADMIN);
        } else {
            model.setType(RoleType.USER);
        }
        model.setCompanyId(account.getCompanyId());
        BeanUtils.copyProperties(request, model);
        userService.insert(model);
        return model;
    }

    @PutMapping
    @Permission(code = "SYSTEM_ACCOUNT")
    public UserModel updateData(HttpServletRequest httpRequest,
                                @RequestBody UserRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        UserModel model = userService.getById(request.getId());
        if (model == null || account.getCompanyId().equals(model.getCompanyId())) {
            throw new CustomException("账号信息不存在");
        }
        model.setNickname(request.getNickname());
        model.setMobilePhone(request.getMobilePhone());
        userService.update(model);
        return model;
    }

    @DeleteMapping
    @ApiOperation("删除")
    @Permission(code = "SYSTEM_ACCOUNT")
    public ReturnResp delete(HttpServletRequest httpRequest,
                             @RequestParam("id") long id) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        UserModel model = userService.getById(id);
        if (model != null && account.getCompanyId().equals(model.getCompanyId())) {
            userService.delete(model);
            return ReturnResp.buildOk();
        } else {
            throw new CustomException("用户不存在");
        }
    }

    @GetMapping("{id}")
    @ApiOperation("详情")
    @Permission(code = "SYSTEM_ACCOUNT")
    public UserModel getDetails(@PathVariable("id") long id) {
        UserModel model = userService.getById(id);
        if (model == null) {
            throw new CustomException("信息不存在");
        }
        return model;
    }

    @PostMapping("pwd")
    @Permission(code = "SYSTEM_ACCOUNT")
    public ReturnResp updatePwd(HttpServletRequest httpRequest,
                                @RequestBody UserPwdRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);

        UserModel userModel = userService.getById(request.getUserId());

        if (account.getCompanyId() > 0 && !account.getCompanyId().equals(userModel.getCompanyId())) {
            throw new CustomException("用户不存在");
        }

        userService.updatePwd(userModel.getId(), request.getNewPassword());

        return ReturnResp.buildOk();
    }

    @GetMapping("role")
    @Permission(code = "SYSTEM_ACCOUNT")
    public ReturnResp getRoleList(HttpServletRequest httpRequest,
                                  @RequestParam(value = "userId", required = false) Long userId) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        if (userId != null) {
            return ReturnResp.buildOk(roleService.getListByUserId(userId));
        } else {
            return ReturnResp.buildOk(roleService.getListByTenantId(account.getCompanyId()));
        }
    }

    @GetMapping("res")
    @Permission(code = "SYSTEM_ACCOUNT")
    public ReturnResp getResList(HttpServletRequest httpRequest) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        return ReturnResp.buildOk(roleService.getResourceByUserId(account.getId()));
    }

    @PutMapping("role")
    @Permission(code = "SYSTEM_ACCOUNT")
    public ReturnResp updateRole(HttpServletRequest httpRequest,
                                 @RequestBody UserRoleRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);

        UserModel userModel = userService.getById(request.getUserId());

        if (userModel == null || (account.getCompanyId() > 0 && !account.getCompanyId().equals(userModel.getCompanyId()))) {
            throw new CustomException("用户不存在");
        }

        userService.updateRole(userModel.getId(), request.getRoleIds());

        return ReturnResp.buildOk();
    }

    @PostMapping("enable")
    @ApiOperation("禁用/启动账号")
    @Permission(code = "SYSTEM_ACCOUNT")
    public ReturnResp enable(HttpServletRequest httpRequest,
                             @RequestBody EnableRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        UserModel model = userService.getById(request.getUserId());

        if (model == null || (account.getCompanyId() > 0 && !account.getCompanyId().equals(model.getCompanyId()))) {
            throw new CustomException("用户不存在");
        }
        CommonStatus status = request.isFlag() ? CommonStatus.ENABLE : CommonStatus.DISABLE;
        model.setStatus(status);
        userService.update(model);
        return ReturnResp.buildOk();
    }
}
